const Koa = require("koa");
const router = require("koa-router")(); //路由
const static = require("koa-static"); //静态资源
const views = require("koa-views"); //解析模板
const nunjucks = require("nunjucks"); //模板引擎
const parser = require("koa-parser"); //解析post
const session = require("koa-session"); //session npmjs.com查依赖包

const app = new Koa();

app.keys = ["123456"];
const CONFIG = {
  maxAge: 1000 * 60,
};
app.use(session(CONFIG, app));

app.use(static(__dirname + "/static"));
app.use(
  views(__dirname + "/views", {
    map: { html: "nunjucks", json: "nunjucks" },
  })
);
app.use(parser());

//路由 请求
router.get("/", async (ctx) => {
  //给客户端一个cookie
  // ctx.cookies.set("user", "herry", {
  //   maxAge: 5000, //cookie期限 5s
  // });
  //给客户端一个session
  ctx.session.user = "herry";
  await ctx.render("index.html", {
    name: "herry",
  });
});
router.get("/video", async (ctx) => {
  // let cookie_user = ctx.cookies.get("user");
  //取session
  session_user = ctx.session.user;
  await ctx.render("video.html", { name: "herry", session_user });
});
router.get("/login", async (ctx) => {
  const { username, password } = ctx.query;
  await ctx.render("home.html", { username, password });
});
router.post("/login", async (ctx) => {
  const { username, password } = ctx.request.body;
  let code = -1,
    message = "登录失败";
  if (username === "admin" && password === "123456") {
    code = 200;
    message = "登录成功";
  }
  await ctx.render("home.html", {
    code,
    message,
  });
});
router.get("/a.json", async (ctx) => {
  await ctx.render("json/a", {
    a: 111,
  });
});
app.use(router.routes());

// app.use(async (ctx, next) => {
//   ctx.body = `<h1>111</h1>`;
//   await next(); //执行下一个异步
// });

// app.use(async (ctx, next) => {
//   console.log("函数2");
// });

app.listen(3000, () => {
  console.log("服务器运行成功");
});
